<?php
namespace Cyfy\Modules\Text2Image;

class Text2Image
{
    private $content, $bgcolor, $color, $font, $size;
    private $image;
    private $done;
    
    function __construct($content, $color="#000000", $bgcolor="#FFFFFF", $font = "arial.ttf", $size = 12){
        $this -> content = $content;
        $this -> colors($color,$bgcolor);
        $this -> font($font,$size);
        $this -> done = false;
    }
    
    function colors($color="#000000",$bgcolor="#FFFFFF"){
        $this -> color = $color;
        $this -> bgcolor = $bgcolor;
    }
    
    function font($font, $size){
        if($font)        $this -> font = realpath("fonts/" . $font);
        if($size)        $this -> size = $size;
    }
    
    private function ImageColorAllocateFromHex($color){
        $rgb = sscanf($color, '#%2x%2x%2x'); // djcassis at gmail dot com
        return ImageColorAllocate($this -> image, $rgb[0], $rgb[1], $rgb[2]);
    }
    
    private function process(){
        
        if($this -> done == true){
            return true;
        }
        $textBox = imageftbbox($this -> size, 0, $this -> font, $this -> content);
        
        $w = ceil($textBox[2] * 1.09); // distance from left to right
        $h = ceil((abs($textBox[1]) + $this -> size)*1.5); 

        
        
        //$h = 550;    $this -> content = print_r($textBox,1);
        
        //$h =+ round($h/100*130);

        $x = round(($w - $textBox[2])/2);
        $y = ceil($this -> size * 1.05);
     // $y = $h / 2;
    //    $y =+ round($y/100*150);
    
        $this -> image = imagecreatetruecolor($w,$h);
        imageantialias($this -> image,true);
        imagefilledrectangle($this -> image, 0, 0, $w, $h, $this->ImageColorAllocateFromHex($this->bgcolor));        
        imagefttext($this -> image, $this -> size, 0, $x, $y, $this->ImageColorAllocateFromHex($this->color), $this -> font, $this -> content);
        
        
        $this -> done = true;
    }

    function saveAs($filename){
        $this -> process();
        return imagepng($this -> image,$filename);
    }
    
    function view(){
        $this -> process();
        header ('Content-type: image/png');
        imagepng($this -> image);
    }
}
